package com.limbo.showapp.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.limbo.showapp.R;
import com.limbo.showapp.base.BaseActivity;
import com.limbo.showapp.pop.DownPopupWindow;
import com.limbo.showapp.presenter.DownloadPresenter;
import com.limbo.showapp.util.DisplayUtils;
import com.limbo.showapp.util.MyUtils;
import com.limbo.showapp.util.SPUtils;
import com.limbo.showapp.util.ToastUtils;
import com.limbo.showapp.view.IDownloadView;
import com.limbo.showapp.widget.OnMultiClickListener;
import com.limbo.showapp.widget.SimpleOptionView;

import java.io.File;

/**
 * Created by wangqi on 2018/9/5.
 */

public class CartoonDispalyActivity extends BaseActivity<IDownloadView, DownloadPresenter> implements IDownloadView, OnPageChangeListener {

    private static String CATOON_NAME = "/%s.pdf";

    private File file;
    private PDFView pdfView;

    private String name;
    private String url;
    private SimpleOptionView simpleTileView;
    private ImageView ivNext;

    //资源号
    private int number = 1;//几章
    private int page; //几页
    private DownPopupWindow downPopupWindow;

    private boolean isDowning;

    @Override
    protected DownloadPresenter getPresenter() {
        return new DownloadPresenter();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pdf_display;
    }

    @Override
    public void initView() {
        url = getIntent().getStringExtra("url");

        downPopupWindow = new DownPopupWindow(this);
        pdfView = findViewById(R.id.pdf_view);
        simpleTileView = findViewById(R.id.simpleTileView);
        ivNext = findViewById(R.id.iv_next);
        DisplayUtils.initAfterSetContentView(this, simpleTileView);

        name = url.substring(url.lastIndexOf("/"));
        number = SPUtils.getIntger(this, name, 1);
        page = SPUtils.getIntger(this, name + name, 0);

        simpleTileView.setTitle(name.substring(1));
        simpleTileView.setRightText("章节", onMultiClickListener);
        ivNext.setOnClickListener(onMultiClickListener);
    }

    @Override
    public void initData() {
        File dirFile = new File(getCacheDir().getAbsolutePath() + name);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }

        simpleTileView.postDelayed(new Runnable() {
            @Override
            public void run() {
                //开始下载
                downPdf();
            }
        }, 300);
    }

    private void downPdf() {
        String path = String.format(getCacheDir().getAbsolutePath() + name + CATOON_NAME, number);

        this.file = new File(path);
        if (!this.file.exists()) {
            //下载
            mPresenter.down(String.format(url + CATOON_NAME, number), path);
        } else {
            showPdf();
        }
    }

    //开始展示
    private void showPdf() {
        SPUtils.setIntger(this, name, number);

        pdfView.fromFile(file)
                .defaultPage(page)
                .onPageChange(this)
                .onError(new OnErrorListener() {
                    @Override
                    public void onError(Throwable t) {
                        file.delete();
                        initData();
                    }
                })
//                .swipeHorizontal(false)
//                .pageSnap(true)
//                .autoSpacing(true)
//                .pageFling(true)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        if (page >= pageCount - 2) {
            ivNext.setVisibility(View.VISIBLE);
        } else {
            ivNext.setVisibility(View.GONE);
        }
        SPUtils.setIntger(this, name + name, page);
    }

    View.OnClickListener onMultiClickListener = new OnMultiClickListener() {
        @Override
        public void onMultiClick(View v) {
            switch (v.getId()) {
                case R.id.iv_next:
                    number++;
                    page = 0;
                    downPdf();
                    break;
                case R.id.right_parent:

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onDownStart() {
        isDowning = true;
        downPopupWindow.show(simpleTileView);
    }

    @Override
    public void onDownProgress(final int progress) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                downPopupWindow.setProgress(progress);
            }
        });
    }

    @Override
    public void onDownFail(String errorInfo) {
        if (errorInfo.contains("Not Found")) {
            ToastUtils.getInstanc(mContext).showToast("无更多内容");
        }
        isDowning = false;
        downPopupWindow.dismiss();
    }

    @Override
    public void onDownFinish() {
        isDowning = false;
        downPopupWindow.dismiss();
        showPdf();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (isDowning)
            file.delete();
    }

    public static void OpenActivity(Context context, String url) {
        Intent intent = new Intent(context, CartoonDispalyActivity.class);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }
}
